<?php
// 修复路径问题 - 使用绝对路径
$adminDir = __DIR__;
$projectRoot = dirname($adminDir);

require_once $projectRoot . '/config/config.php';
require_once $projectRoot . '/includes/auth.php';
require_once $projectRoot . '/includes/database.php';

// session已由config/config.php统一管理，无需重复调用

// 检查登录状态
requireLogin();

// 简单的重定向函数
function redirect($url) {
    header("Location: " . $url);
    exit;
}

// 初始化数据库
$db = new Database();

// 获取系统设置（包含动态标题）
$settings = $db->getSettings();
$siteTitle = $settings['site_title'] ?? SITE_TITLE;

// 处理文件上传
function handleImageUpload($file) {
    if (!isset($file) || $file['error'] !== UPLOAD_ERR_OK) {
        return false;
    }
    
    $allowed = ['jpg', 'jpeg', 'png', 'gif', 'ico', 'svg'];
    $filename = $file['name'];
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    
    if (!in_array($ext, $allowed)) {
        return false;
    }
    
    $newName = uniqid() . '.' . $ext;
    $uploadPath = ICON_DIR . '/' . $newName;
    
    if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
        return getUrl('uploads/icons/' . $newName);
    }
    
    return false;
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add') {
        $icon = '';
        $iconType = $_POST['icon_type'] ?? 'class';
        
        if ($iconType === 'upload' && isset($_FILES['icon_file'])) {
            $uploadResult = handleImageUpload($_FILES['icon_file']);
            if ($uploadResult) {
                $icon = $uploadResult;
                $iconType = 'url';
            } else {
                $error = '图标上传失败！';
            }
        } else {
            $icon = sanitizeInput($_POST['icon']);
        }
        
        if (!isset($error)) {
            $data = [
                'name' => sanitizeInput($_POST['name']),
                'short_name' => sanitizeInput($_POST['short_name']),
                'icon' => $icon,
                'icon_type' => $iconType,
                'display_style' => sanitizeInput($_POST['display_style']),
                'sort' => (int)$_POST['sort']
            ];
            
            if ($db->addCategory($data)) {
                $_SESSION['success_message'] = '分类添加成功！';
            } else {
                $_SESSION['error_message'] = '分类添加失败！';
            }
            redirect(getUrl('admin/categories'));
        } else {
            $_SESSION['error_message'] = $error;
            redirect(getUrl('admin/categories'));
        }
    } elseif ($action === 'edit') {
        $id = (int)$_POST['id'];
        $icon = $_POST['current_icon'] ?? '';
        $iconType = $_POST['icon_type'] ?? 'class';
        
        if ($iconType === 'upload' && isset($_FILES['icon_file']) && $_FILES['icon_file']['error'] === UPLOAD_ERR_OK) {
            $uploadResult = handleImageUpload($_FILES['icon_file']);
            if ($uploadResult) {
                $icon = $uploadResult;
                $iconType = 'url';
            }
        } elseif ($iconType === 'class') {
            $icon = sanitizeInput($_POST['icon']);
        }
        
        $data = [
            'name' => sanitizeInput($_POST['name']),
            'short_name' => sanitizeInput($_POST['short_name']),
            'icon' => $icon,
            'icon_type' => $iconType,
            'display_style' => sanitizeInput($_POST['display_style']),
            'sort' => (int)$_POST['sort']
        ];
        
        if ($db->updateCategory($id, $data)) {
            $_SESSION['success_message'] = '分类更新成功！';
        } else {
            $_SESSION['error_message'] = '分类更新失败！';
        }
        redirect(getUrl('admin/categories'));
    } elseif ($action === 'delete') {
        $id = (int)$_POST['id'];
        if ($db->deleteCategory($id)) {
            $_SESSION['success_message'] = '分类删除成功！';
        } else {
            $_SESSION['error_message'] = '分类删除失败！';
        }
        redirect(getUrl('admin/categories'));
    }
}

// 获取并清除消息
$success_message = $_SESSION['success_message'] ?? null;
unset($_SESSION['success_message']);

$error_message = $_SESSION['error_message'] ?? null;
unset($_SESSION['error_message']);

// 获取分类列表
$categories = $db->getCategories();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>分类管理 - <?php echo $siteTitle; ?></title>
    
    <!-- 样式文件 -->
    <link rel="stylesheet" href="<?php echo asset('css/admin.css'); ?>">
    <link rel="stylesheet" href="<?php echo asset('libs/fontawesome/all.min.css'); ?>">
    
    <!-- 网站图标 -->
    <link rel="icon" type="image/x-icon" href="<?php echo asset('images/favicon.ico'); ?>">
</head>
<body class="admin-page">
    <!-- 侧边栏 -->
    <aside class="sidebar">
        <div class="sidebar-header">
            <div class="logo">
                <i class="fas fa-compass"></i>
                <h2><?php echo $siteTitle; ?></h2>
            </div>
        </div>
        
        <nav class="sidebar-nav">
            <ul>
                <li>
                    <a href="<?php echo getUrl('admin/'); ?>">
                        <i class="fas fa-tachometer-alt"></i>
                        <span>仪表盘</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo getUrl('admin/navigations'); ?>">
                        <i class="fas fa-link"></i>
                        <span>导航管理</span>
                    </a>
                </li>
                <li class="active">
                    <a href="<?php echo getUrl('admin/categories'); ?>">
                        <i class="fas fa-folder"></i>
                        <span>分类管理</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo getUrl('admin/tags'); ?>">
                        <i class="fas fa-tags"></i>
                        <span>标签管理</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo getUrl('admin/settings'); ?>">
                        <i class="fas fa-cog"></i>
                        <span>系统设置</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo getUrl(); ?>" target="_blank">
                        <i class="fas fa-external-link-alt"></i>
                        <span>访问前台</span>
                    </a>
                </li>
            </ul>
        </nav>
        
        <div class="sidebar-footer">
            <div class="user-info">
                <i class="fas fa-user-circle"></i>
                <span><?php echo $_SESSION['admin_username'] ?? 'Admin'; ?></span>
            </div>
            <a href="<?php echo getUrl('admin/index.php?action=logout'); ?>" class="logout-btn" title="退出登录">
                <i class="fas fa-sign-out-alt"></i>
            </a>
        </div>
    </aside>
    
    <!-- 主要内容区域 -->
    <main class="main-content">
        <!-- 顶部栏 -->
        <header class="content-header">
            <div class="header-left">
                <h1><i class="fas fa-folder"></i> 分类管理</h1>
                <p>管理导航分类，支持创建、编辑和删除操作。</p>
            </div>
            <div class="header-right">
                <button class="btn btn-primary" onclick="showAddModal()">
                    <i class="fas fa-plus"></i> 添加分类
                </button>
            </div>
        </header>
        
        <!-- 消息提示 -->
        <?php if (isset($success_message)): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i>
                <?php echo $success_message; ?>
            </div>
        <?php endif; ?>
        
        <?php if (isset($error_message)): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle"></i>
                <?php echo $error_message; ?>
            </div>
        <?php endif; ?>
        
        <!-- 分类列表 -->
        <section class="content-section">
            <div class="card">
                <div class="card-header">
                    <h3><i class="fas fa-list"></i> 分类列表</h3>
                    <p>共 <?php echo count($categories); ?> 个分类</p>
                </div>
                <div class="card-body">
                    <?php if (!empty($categories)): ?>
                        <div class="table-responsive">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>图标</th>
                                        <th>名称</th>
                                        <th>类名缩写</th>
                                        <th>显示样式</th>
                                        <th>排序</th>
                                        <th>标签数量</th>
                                        <th>创建时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($categories as $category): ?>
                                        <tr>
                                            <td><?php echo $category['id']; ?></td>
                                            <td>
                                                <?php if (isset($category['icon_type']) && $category['icon_type'] === 'url'): ?>
                                                    <img src="<?php echo htmlspecialchars($category['icon']); ?>" 
                                                         alt="<?php echo htmlspecialchars($category['name']); ?>"
                                                         style="width: 20px; height: 20px;">
                                                <?php else: ?>
                                                    <i class="<?php echo htmlspecialchars($category['icon']); ?>"></i>
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo htmlspecialchars($category['name']); ?></td>
                                            <td><?php echo htmlspecialchars($category['short_name'] ?? ''); ?></td>
                                            <td>
                                                <?php
                                                $styleNames = [
                                                    'STYLE_1' => '样式一',
                                                    'STYLE_2' => '样式二',
                                                    'STYLE_3' => '样式三',
                                                    'STYLE_4' => '样式四',
                                                    'STYLE_5' => '样式五'
                                                ];
                                                $displayStyle = $category['display_style'] ?? 'STYLE_1';
                                                echo '<span class="badge badge-info">' . htmlspecialchars($styleNames[$displayStyle] ?? '默认') . '</span>';
                                                ?>
                                            </td>
                                            <td><?php echo $category['sort']; ?></td>
                                            <td>
                                                <span class="badge badge-info"><?php echo $db->getTagCountByCategory($category['id']); ?></span>
                                            </td>
                                            <td><?php echo $category['created_at']; ?></td>
                                            <td>
                                                <div class="btn-group">
                                                    <button class="btn btn-sm btn-outline-primary" 
                                                            onclick="editCategory(<?php echo htmlspecialchars(json_encode($category)); ?>)">
                                                        <i class="fas fa-edit"></i> 编辑
                                                    </button>
                                                    <button class="btn btn-sm btn-outline-danger" 
                                                            onclick="deleteCategory(<?php echo $category['id']; ?>, '<?php echo htmlspecialchars($category['name']); ?>')">
                                                        <i class="fas fa-trash"></i> 删除
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="empty-state">
                            <i class="fas fa-folder-open"></i>
                            <h3>暂无分类</h3>
                            <p>还没有创建任何分类，点击上方按钮开始添加。</p>
                            <button class="btn btn-primary" onclick="showAddModal()">
                                <i class="fas fa-plus"></i> 添加第一个分类
                            </button>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </section>
    </main>
    
    <!-- 添加/编辑分类模态框 -->
    <div id="categoryModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle">添加分类</h3>
                <button class="close-btn" onclick="closeModal()">&times;</button>
            </div>
            <form method="POST" enctype="multipart/form-data" class="modal-body">
                <input type="hidden" name="action" id="formAction" value="add">
                <input type="hidden" name="id" id="categoryId">
                <input type="hidden" name="current_icon" id="currentIcon">
                
                <div class="form-group">
                    <label for="name">分类名称 *</label>
                    <input type="text" id="name" name="name" required placeholder="请输入分类名称">
                </div>

                <div class="form-group">
                    <label for="short_name">类名缩写 *</label>
                    <input type="text" id="short_name" name="short_name" required placeholder="请输入类名缩写，如：图库、工具等">
                </div>
                
                <div class="form-group">
                    <label>图标设置 *</label>
                    <div class="icon-options">
                        <label class="radio-option">
                            <input type="radio" name="icon_type" value="class" checked onchange="toggleIconInput()">
                            <span>Font Awesome 图标</span>
                        </label>
                        <label class="radio-option">
                            <input type="radio" name="icon_type" value="upload" onchange="toggleIconInput()">
                            <span>上传图标文件</span>
                        </label>
                    </div>
                    
                    <div id="iconClassInput">
                        <div class="icon-input-group">
                            <div class="selected-icon-display" onclick="showIconPicker()">
                                <i id="selectedIconPreview" class="fas fa-question-circle"></i>
                                <div class="icon-display-text">
                                    <span id="selectedIconText">请选择图标</span>
                                    <small class="icon-class-text" id="selectedIconClass">点击选择</small>
                                </div>
                                <i class="fas fa-chevron-down icon-dropdown-arrow"></i>
                            </div>
                            <input type="text" id="icon" name="icon" placeholder="或手动输入：fas fa-star" 
                                   onchange="updateIconPreview(this.value)">
                        </div>
                        <small class="form-text">点击按钮选择图标，或手动输入 Font Awesome 图标类名</small>
                    </div>
                    
                    <div id="iconFileInput" style="display: none;">
                        <label for="icon_file">上传图标</label>
                        <div class="image-preview-container">
                            <img id="imagePreview" src="#" alt="图标预览" style="display: none;">
                            <span id="imagePreviewText">暂无预览</span>
                        </div>
                        <input type="file" id="icon_file" name="icon_file" accept="image/*,image/svg+xml">
                        <small>推荐尺寸：64x64px，支持jpg, png, gif, ico, svg</small>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="display_style">显示样式 *</label>
                    <select id="display_style" name="display_style" required>
                        <option value="">请选择显示样式</option>
                        <option value="STYLE_1">样式一 - 中等图片+名称+描述+标签</option>
                        <option value="STYLE_2">样式二 - 小图左+名称右</option>
                        <option value="STYLE_3">样式三 - 大图+名称+描述+标签</option>
                        <option value="STYLE_4">样式四 - 无图片+名称左+描述右</option>
                        <option value="STYLE_5">样式五 - 小图+名称+描述+标签</option>
                    </select>
                    <small class="form-text">选择该分类下导航项的显示样式</small>
                </div>

                <div class="form-group">
                    <label for="sort">排序序号 *</label>
                    <input type="number" id="sort" name="sort" required placeholder="数字越大排序越靠前" min="1">
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">取消</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> 保存
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 删除确认模态框 -->
    <div id="deleteModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>确认删除</h3>
                <button class="close-btn" onclick="closeDeleteModal()">&times;</button>
            </div>
            <div class="modal-body">
                <p>确定要删除分类 "<span id="deleteCategoryName"></span>" 吗？</p>
                <p class="text-danger">注意：删除分类将同时删除该分类下的所有导航链接！</p>
                <form method="POST" style="display: none;" id="deleteForm">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" id="deleteCategoryId">
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeDeleteModal()">取消</button>
                <button type="button" class="btn btn-danger" onclick="confirmDelete()">
                    <i class="fas fa-trash"></i> 确认删除
                </button>
            </div>
        </div>
    </div>
    
    <!-- 图标选择器模态框 -->
    <div id="iconPickerModal" class="modal">
        <div class="modal-content modal-lg">
            <div class="modal-header">
                <h3>选择 Font Awesome 图标</h3>
                <button class="close-btn" onclick="closeIconPicker()">&times;</button>
            </div>
            <div class="modal-body">
                <div class="icon-search-box">
                    <input type="text" id="iconSearch" placeholder="搜索图标..." onkeyup="filterIcons(this.value)">
                </div>
                <div class="icon-categories">
                    <button class="icon-category-btn active" onclick="showIconCategory('all')">全部</button>
                    <button class="icon-category-btn" onclick="showIconCategory('common')">常用</button>
                    <button class="icon-category-btn" onclick="showIconCategory('web')">网站</button>
                    <button class="icon-category-btn" onclick="showIconCategory('social')">社交</button>
                    <button class="icon-category-btn" onclick="showIconCategory('business')">商务</button>
                    <button class="icon-category-btn" onclick="showIconCategory('tech')">技术</button>
                </div>
                <div class="icon-grid" id="iconGrid">
                    <!-- 图标将通过JavaScript动态生成 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeIconPicker()">取消</button>
            </div>
        </div>
    </div>
    
    <script>
        // Font Awesome 图标数据
        const fontAwesomeIcons = {
            common: [
                { class: 'fas fa-home', name: '首页' },
                { class: 'fas fa-house', name: '房屋' },
                { class: 'fas fa-user', name: '用户' },
                { class: 'fas fa-users', name: '用户组' },
                { class: 'fas fa-star', name: '星标' },
                { class: 'fas fa-heart', name: '喜欢' },
                { class: 'fas fa-search', name: '搜索' },
                { class: 'fas fa-magnifying-glass', name: '搜索' },
                { class: 'fas fa-envelope', name: '邮件' },
                { class: 'fas fa-phone', name: '电话' },
                { class: 'fas fa-calendar', name: '日历' },
                { class: 'fas fa-clock', name: '时钟' },
                { class: 'fas fa-location-dot', name: '位置' },
                { class: 'fas fa-shopping-cart', name: '购物车' },
                { class: 'fas fa-download', name: '下载' },
                { class: 'fas fa-upload', name: '上传' },
                { class: 'fas fa-edit', name: '编辑' },
                { class: 'fas fa-trash', name: '删除' },
                { class: 'fas fa-plus', name: '添加' },
                { class: 'fas fa-minus', name: '减少' },
                { class: 'fas fa-check', name: '确认' },
                { class: 'fas fa-times', name: '关闭' },
                { class: 'fas fa-cog', name: '设置' },
                { class: 'fas fa-info-circle', name: '信息' },
                { class: 'fas fa-exclamation-triangle', name: '警告' },
                { class: 'fas fa-question-circle', name: '帮助' },
                { class: 'fas fa-thumbs-up', name: '赞' },
                { class: 'fas fa-thumbs-down', name: '踩' },
                { class: 'fas fa-share', name: '分享' },
                { class: 'fas fa-link', name: '链接' },
                { class: 'fas fa-eye', name: '查看' },
                { class: 'fas fa-print', name: '打印' },
                { class: 'fas fa-bookmark', name: '书签' },
                { class: 'fas fa-bell', name: '通知' },
                { class: 'fas fa-lock', name: '锁定' },
                { class: 'fas fa-unlock', name: '解锁' },
                { class: 'fas fa-shield', name: '安全' },
                { class: 'fas fa-fire', name: '火热' },
                { class: 'fas fa-bolt', name: '闪电' },
                { class: 'fas fa-tag', name: '标签' },
                { class: 'fas fa-tags', name: '标签组' },
                { class: 'fas fa-flag', name: '旗帜' },
                { class: 'fas fa-copy', name: '复制' },
                { class: 'fas fa-folder', name: '文件夹' },
                { class: 'fas fa-file', name: '文件' },
                { class: 'fas fa-image', name: '图片' },
                { class: 'fas fa-music', name: '音乐' },
                { class: 'fas fa-video', name: '视频' },
                { class: 'fas fa-comment', name: '评论' },
                { class: 'fas fa-comments', name: '聊天' },
                { class: 'fas fa-filter', name: '过滤' },
                { class: 'fas fa-sort', name: '排序' },
                { class: 'fas fa-list', name: '列表' },
                { class: 'fas fa-table', name: '表格' },
                { class: 'fas fa-bars', name: '菜单' },
                { class: 'fas fa-ellipsis', name: '更多' },
                { class: 'fas fa-circle', name: '圆形' },
                { class: 'fas fa-square', name: '方形' },
                { class: 'fas fa-arrows-rotate', name: '刷新' },
                { class: 'fas fa-power-off', name: '电源' }
            ],
            web: [
                { class: 'fab fa-github', name: 'GitHub' },
                { class: 'fab fa-google', name: 'Google' },
                { class: 'fab fa-microsoft', name: 'Microsoft' },
                { class: 'fab fa-apple', name: 'Apple' },
                { class: 'fab fa-amazon', name: 'Amazon' },
                { class: 'fab fa-youtube', name: 'YouTube' },
                { class: 'fab fa-react', name: 'React' },
                { class: 'fab fa-vuejs', name: 'Vue.js' },
                { class: 'fab fa-angular', name: 'Angular' },
                { class: 'fab fa-bootstrap', name: 'Bootstrap' },
                { class: 'fab fa-docker', name: 'Docker' },
                { class: 'fab fa-python', name: 'Python' },
                { class: 'fab fa-java', name: 'Java' },
                { class: 'fab fa-js-square', name: 'JavaScript' },
                { class: 'fab fa-html5', name: 'HTML5' },
                { class: 'fab fa-css3-alt', name: 'CSS3' },
                { class: 'fab fa-wordpress', name: 'WordPress' },
                { class: 'fab fa-laravel', name: 'Laravel' },
                { class: 'fab fa-figma', name: 'Figma' },
                { class: 'fab fa-chrome', name: 'Chrome' },
                { class: 'fab fa-firefox', name: 'Firefox' },
                { class: 'fas fa-globe', name: '网站' },
                { class: 'fas fa-blog', name: '博客' },
                { class: 'fas fa-server', name: '服务器' },
                { class: 'fas fa-database', name: '数据库' },
                { class: 'fas fa-cloud', name: '云服务' },
                { class: 'fas fa-code', name: '代码' },
                { class: 'fas fa-terminal', name: '终端' },
                { class: 'fas fa-laptop-code', name: '编程' },
                { class: 'fas fa-bug', name: '调试' },
                { class: 'fas fa-network-wired', name: '网络' },
                { class: 'fas fa-wifi', name: 'WiFi' },
                { class: 'fas fa-sitemap', name: '网站地图' },
                { class: 'fas fa-rocket', name: '发布' }
            ],
            social: [
                { class: 'fab fa-facebook', name: 'Facebook' },
                { class: 'fab fa-twitter', name: 'Twitter' },
                { class: 'fab fa-instagram', name: 'Instagram' },
                { class: 'fab fa-linkedin', name: 'LinkedIn' },
                { class: 'fab fa-youtube', name: 'YouTube' },
                { class: 'fab fa-tiktok', name: 'TikTok' },
                { class: 'fab fa-wechat', name: '微信' },
                { class: 'fab fa-weibo', name: '微博' },
                { class: 'fab fa-qq', name: 'QQ' },
                { class: 'fab fa-discord', name: 'Discord' },
                { class: 'fab fa-telegram', name: 'Telegram' },
                { class: 'fab fa-whatsapp', name: 'WhatsApp' },
                { class: 'fab fa-slack', name: 'Slack' },
                { class: 'fab fa-skype', name: 'Skype' },
                { class: 'fab fa-twitch', name: 'Twitch' },
                { class: 'fab fa-medium', name: 'Medium' },
                { class: 'fab fa-tumblr', name: 'Tumblr' },
                { class: 'fab fa-spotify', name: 'Spotify' },
                { class: 'fab fa-zhihu', name: '知乎' },
                { class: 'fas fa-comment', name: '评论' },
                { class: 'fas fa-comments', name: '聊天' },
                { class: 'fas fa-users', name: '用户群' },
                { class: 'fas fa-at', name: '@符号' },
                { class: 'fas fa-hashtag', name: '话题标签' },
                { class: 'fas fa-share', name: '分享' }
            ],
            business: [
                { class: 'fas fa-briefcase', name: '公文包' },
                { class: 'fas fa-building', name: '建筑' },
                { class: 'fas fa-store', name: '商店' },
                { class: 'fas fa-chart-bar', name: '柱状图' },
                { class: 'fas fa-chart-line', name: '折线图' },
                { class: 'fas fa-chart-pie', name: '饼图' },
                { class: 'fas fa-dollar-sign', name: '美元' },
                { class: 'fas fa-yen-sign', name: '日元' },
                { class: 'fas fa-euro-sign', name: '欧元' },
                { class: 'fas fa-credit-card', name: '信用卡' },
                { class: 'fas fa-money-bill', name: '纸币' },
                { class: 'fas fa-coins', name: '硬币' },
                { class: 'fas fa-wallet', name: '钱包' },
                { class: 'fas fa-handshake', name: '握手' },
                { class: 'fas fa-trophy', name: '奖杯' },
                { class: 'fas fa-award', name: '奖项' },
                { class: 'fas fa-crown', name: '皇冠' },
                { class: 'fas fa-target', name: '目标' },
                { class: 'fas fa-rocket', name: '火箭' },
                { class: 'fas fa-lightbulb', name: '灯泡' },
                { class: 'fas fa-calculator', name: '计算器' },
                { class: 'fas fa-gavel', name: '法官锤' },
                { class: 'fas fa-signature', name: '签名' },
                { class: 'fas fa-file-contract', name: '合同' },
                { class: 'fas fa-file-invoice', name: '发票' },
                { class: 'fas fa-clipboard-check', name: '检查清单' },
                { class: 'fas fa-tasks', name: '任务' },
                { class: 'fas fa-project-diagram', name: '项目图' },
                { class: 'fas fa-users-gear', name: '团队管理' },
                { class: 'fas fa-user-tie', name: '商务人员' },
                { class: 'fas fa-tools', name: '工具' },
                { class: 'fas fa-warehouse', name: '仓库' },
                { class: 'fas fa-shipping-fast', name: '快递' },
                { class: 'fas fa-truck', name: '卡车' },
                { class: 'fas fa-percent', name: '百分比' }
            ],
            tech: [
                { class: 'fas fa-laptop', name: '笔记本' },
                { class: 'fas fa-mobile-alt', name: '手机' },
                { class: 'fas fa-tablet-alt', name: '平板' },
                { class: 'fas fa-desktop', name: '桌面' },
                { class: 'fas fa-tv', name: '电视' },
                { class: 'fas fa-keyboard', name: '键盘' },
                { class: 'fas fa-mouse', name: '鼠标' },
                { class: 'fas fa-headphones', name: '耳机' },
                { class: 'fas fa-microphone', name: '麦克风' },
                { class: 'fas fa-camera', name: '相机' },
                { class: 'fas fa-video', name: '视频' },
                { class: 'fas fa-wifi', name: 'WiFi' },
                { class: 'fas fa-signal', name: '信号' },
                { class: 'fas fa-bluetooth', name: '蓝牙' },
                { class: 'fas fa-satellite', name: '卫星' },
                { class: 'fas fa-battery-full', name: '满电池' },
                { class: 'fas fa-plug', name: '插头' },
                { class: 'fas fa-usb', name: 'USB' },
                { class: 'fas fa-ethernet', name: '以太网' },
                { class: 'fas fa-hard-drive', name: '硬盘' },
                { class: 'fas fa-memory', name: '内存' },
                { class: 'fas fa-microchip', name: '芯片' },
                { class: 'fas fa-server', name: '服务器' },
                { class: 'fas fa-database', name: '数据库' },
                { class: 'fas fa-cloud', name: '云' },
                { class: 'fas fa-network-wired', name: '有线网络' },
                { class: 'fas fa-robot', name: '机器人' },
                { class: 'fas fa-gamepad', name: '游戏手柄' },
                { class: 'fas fa-microscope', name: '显微镜' },
                { class: 'fas fa-telescope', name: '望远镜' },
                { class: 'fas fa-rocket', name: '火箭' },
                { class: 'fas fa-fingerprint', name: '指纹' },
                { class: 'fas fa-qrcode', name: '二维码' },
                { class: 'fas fa-barcode', name: '条形码' },
                { class: 'fas fa-print', name: '打印' }
            ]
        };

        // 获取所有图标
        function getAllIcons() {
            let allIcons = [];
            for (let category in fontAwesomeIcons) {
                allIcons = allIcons.concat(fontAwesomeIcons[category]);
            }
            return allIcons;
        }

        // 切换图标输入方式
        function toggleIconInput() {
            const iconType = document.querySelector('input[name="icon_type"]:checked').value;
            const classInput = document.getElementById('iconClassInput');
            const fileInput = document.getElementById('iconFileInput');
            const imagePreview = document.getElementById('imagePreview');
            const imagePreviewText = document.getElementById('imagePreviewText');
            
            if (iconType === 'class') {
                classInput.style.display = 'block';
                fileInput.style.display = 'none';
                document.getElementById('icon').required = true;
                document.getElementById('icon_file').required = false;
            } else {
                classInput.style.display = 'none';
                fileInput.style.display = 'block';
                document.getElementById('icon').required = false;
                // 当是新添加时，上传文件是必须的。编辑时不是。
                const isEditing = !!document.getElementById('categoryId').value;
                document.getElementById('icon_file').required = !isEditing;

                if (!imagePreview.src || imagePreview.src.endsWith('#')) {
                    imagePreview.style.display = 'none';
                    imagePreviewText.style.display = 'block';
                } else {
                    imagePreview.style.display = 'block';
                    imagePreviewText.style.display = 'none';
                }
            }
        }

        // 显示图标选择器
        function showIconPicker() {
            document.getElementById('iconPickerModal').classList.add('show');
            showIconCategory('all');
        }

        // 关闭图标选择器
        function closeIconPicker() {
            document.getElementById('iconPickerModal').classList.remove('show');
        }

        // 显示图标分类
        function showIconCategory(category) {
            // 更新分类按钮状态
            document.querySelectorAll('.icon-category-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            event.target.classList.add('active');

            // 获取图标数据
            let icons;
            if (category === 'all') {
                icons = getAllIcons();
            } else {
                icons = fontAwesomeIcons[category] || [];
            }

            // 生成图标网格
            renderIconGrid(icons);
        }

        // 渲染图标网格
        function renderIconGrid(icons) {
            const iconGrid = document.getElementById('iconGrid');
            iconGrid.innerHTML = '';

            icons.forEach(icon => {
                const iconItem = document.createElement('div');
                iconItem.className = 'icon-item';
                iconItem.innerHTML = `
                    <i class="${icon.class}"></i>
                    <span class="icon-name">${icon.name}</span>
                    <span class="icon-class">${icon.class}</span>
                `;
                iconItem.onclick = () => selectIcon(icon.class, icon.name);
                iconGrid.appendChild(iconItem);
            });
        }

        // 选择图标
        function selectIcon(iconClass, iconName) {
            document.getElementById('icon').value = iconClass;
            document.getElementById('selectedIconPreview').className = iconClass;
            document.getElementById('selectedIconText').textContent = iconName;
            document.getElementById('selectedIconClass').textContent = iconClass;
            closeIconPicker();
        }

        // 更新图标预览
        function updateIconPreview(iconClass) {
            if (iconClass && iconClass.trim()) {
                document.getElementById('selectedIconPreview').className = iconClass;
                // 尝试从图标库中找到对应的名称
                const allIcons = getAllIcons();
                const foundIcon = allIcons.find(icon => icon.class === iconClass);
                const iconName = foundIcon ? foundIcon.name : iconClass;
                
                document.getElementById('selectedIconText').textContent = iconName;
                document.getElementById('selectedIconClass').textContent = iconClass;
            } else {
                document.getElementById('selectedIconPreview').className = 'fas fa-question-circle';
                document.getElementById('selectedIconText').textContent = '请选择图标';
                document.getElementById('selectedIconClass').textContent = '点击选择';
            }
        }

        // 搜索图标
        function filterIcons(searchTerm) {
            const allIcons = getAllIcons();
            const filteredIcons = allIcons.filter(icon => 
                icon.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                icon.class.toLowerCase().includes(searchTerm.toLowerCase())
            );
            renderIconGrid(filteredIcons);
        }

        // 显示添加模态框
        function showAddModal() {
            document.getElementById('modalTitle').textContent = '添加分类';
            document.getElementById('formAction').value = 'add';
            document.getElementById('categoryId').value = '';
            document.getElementById('currentIcon').value = '';
            document.getElementById('name').value = '';
            document.getElementById('short_name').value = '';
            document.getElementById('icon').value = '';
            document.getElementById('display_style').value = 'STYLE_1'; // 默认选择样式一
            document.getElementById('sort').value = '';

            // 重置图标选择
            document.querySelector('input[name="icon_type"][value="class"]').checked = true;
            toggleIconInput();
            updateIconPreview('');
            
            // 重置文件上传预览
            const imagePreview = document.getElementById('imagePreview');
            const imagePreviewText = document.getElementById('imagePreviewText');
            imagePreview.src = '#';
            imagePreview.style.display = 'none';
            imagePreviewText.style.display = 'block';
            imagePreviewText.textContent = '暂无预览';
            document.getElementById('icon_file').value = '';
            
            document.getElementById('categoryModal').classList.add('show');
        }
        
        // 编辑分类
        function editCategory(category) {
            document.getElementById('modalTitle').textContent = '编辑分类';
            document.getElementById('formAction').value = 'edit';
            document.getElementById('categoryId').value = category.id;
            document.getElementById('name').value = category.name;
            document.getElementById('short_name').value = category.short_name || '';
            document.getElementById('display_style').value = category.display_style || 'STYLE_1';
            document.getElementById('sort').value = category.sort;

            // 处理图标
            if (category.icon_type === 'url') {
                document.querySelector('input[name="icon_type"][value="upload"]').checked = true;
                document.getElementById('currentIcon').value = category.icon;

                // 显示图片预览
                const imagePreview = document.getElementById('imagePreview');
                const imagePreviewText = document.getElementById('imagePreviewText');
                imagePreview.src = category.icon;
                imagePreview.style.display = 'block';
                imagePreviewText.style.display = 'none';
            } else {
                document.querySelector('input[name="icon_type"][value="class"]').checked = true;
                document.getElementById('icon').value = category.icon;
                document.getElementById('currentIcon').value = category.icon;
                updateIconPreview(category.icon);
            }

            toggleIconInput();
            document.getElementById('categoryModal').classList.add('show');
        }
        
        // 删除分类
        function deleteCategory(id, name) {
            document.getElementById('deleteCategoryId').value = id;
            document.getElementById('deleteCategoryName').textContent = name;
            document.getElementById('deleteModal').classList.add('show');
        }
        
        // 确认删除
        function confirmDelete() {
            document.getElementById('deleteForm').submit();
        }
        
        // 关闭模态框
        function closeModal() {
            document.getElementById('categoryModal').classList.remove('show');
        }
        
        function closeDeleteModal() {
            document.getElementById('deleteModal').classList.remove('show');
        }
        
        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modal = document.getElementById('categoryModal');
            const deleteModal = document.getElementById('deleteModal');
            const iconModal = document.getElementById('iconPickerModal');
            if (event.target === modal) {
                closeModal();
            }
            if (event.target === deleteModal) {
                closeDeleteModal();
            }
            if (event.target === iconModal) {
                closeIconPicker();
            }
        }

        // 文件预览
        document.addEventListener('DOMContentLoaded', function() {
            const iconFileInput = document.getElementById('icon_file');
            if (iconFileInput) {
                iconFileInput.addEventListener('change', function(e) {
                    const file = e.target.files[0];
                    const imagePreview = document.getElementById('imagePreview');
                    const imagePreviewText = document.getElementById('imagePreviewText');
                    
                    if (file) {
                        const reader = new FileReader();
                        reader.onload = function(e) {
                            imagePreview.src = e.target.result;
                            imagePreview.style.display = 'block';
                            imagePreviewText.style.display = 'none';
                        };
                        reader.readAsDataURL(file);
                    } else {
                        imagePreview.src = '#';
                        imagePreview.style.display = 'none';
                        imagePreviewText.style.display = 'block';
                        imagePreviewText.textContent = '暂无预览';
                    }
                });
            }
        });
    </script>
</body>
</html>